package com.chenjian.annotation.servlet;

import com.chenjian.annotation.custom.CustomContext;

import javax.servlet.*;
import java.io.IOException;
import java.util.Enumeration;
import java.util.concurrent.ConcurrentHashMap;

public class InitFilter implements Filter {

    private String BASE_PACKAGE = "basePack";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //解析filter入参
        String filterName = filterConfig.getFilterName();
        String basePack = "";
        Enumeration<String> enumeration = filterConfig.getInitParameterNames();
        while ((enumeration.hasMoreElements())) {
            String nextElement = enumeration.nextElement();
            String parameter = filterConfig.getInitParameter(nextElement);
            if (BASE_PACKAGE.equals(nextElement)) {
                basePack = parameter;
            }
            System.out.println("启动参数-" + nextElement + ":" + parameter);
        }
        try {
            //核心入口
            CustomContext.getCustomContext().customContextInit(basePack);
            ConcurrentHashMap<String, Object> hashMap = CustomContext.getCustomContext().getCustomContextMap();
            for (String s : hashMap.keySet()) {
                System.out.println(s + "===========" + hashMap.get(s));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(filterName + "初始化完成.....");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        System.out.println("销毁");
    }
}
